package cn.edu.tju.core.model;

import cn.edu.tju.elm.model.Order;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.hibernate.annotations.BatchSize;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

@Entity
@Table(name = "users")
@Inheritance(strategy = InheritanceType.JOINED)
public class User extends BaseEntity {

   @Column(name = "USERNAME", length = 100, unique = true)
   @NotNull
   @Size(min = 1, max = 100)
   private String username;

   @JsonIgnore
   @Column(name = "PASSWORD", length = 100)
   @NotNull
   @Size(min = 1, max = 100)
   private String password;

   @JsonIgnore
   @Column(name = "ACTIVATED")
   @NotNull
   private boolean activated;

   @ManyToMany
   @JoinTable(
      name = "USER_AUTHORITY",
      joinColumns = {@JoinColumn(name = "USER_ID", referencedColumnName = "ID")},
      inverseJoinColumns = {@JoinColumn(name = "AUTHORITY_NAME", referencedColumnName = "NAME")})
   @BatchSize(size = 20)
   private Set<Authority> authorities = new HashSet<>();

   public String getUsername() {
      return username;
   }

   public void setUsername(String username) {
      this.username = username;
   }

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

   public boolean isActivated() {
      return activated;
   }

   public void setActivated(boolean activated) {
      this.activated = activated;
   }

   public Set<Authority> getAuthorities() {
      return authorities;
   }

   public void setAuthorities(Set<Authority> authorities) {
      this.authorities = authorities;
   }

   /**
    * 检查用户是否有权限查看其他用户的订单
    * 管理员可以查看所有订单，普通用户只能查看自己的订单
    */
   @Transient
   public boolean hasPermissionToViewOtherOrders() {
       // 检查用户是否是管理员
       return this.getAuthorities().stream()
               .anyMatch(authority -> authority.getName().equals("ROLE_ADMIN"));
   }

   /**
    * 检查用户是否有权限访问特定订单
    * 用户可以访问自己的订单，管理员可以访问所有订单
    */
   @Transient
   public boolean hasPermissionToAccessOrder(Order order) {
       // 用户可以访问自己的订单
       if (this.getId().equals(order.getCustomer().getId())) {
           return true;
       }
       
       // 管理员可以访问所有订单
       return hasPermissionToViewOtherOrders();
   }

   @Override
   public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;
      User user = (User) o;
      return this.getId().equals(user.getId());
   }

   @Override
   public int hashCode() {
      return Objects.hash(this.getId());
   }

   @Override
   public String toString() {
      return "User{" +
         "username='" + username + '\'' +
         ", password='" + password + '\'' +
         ", activated=" + activated +
         '}';
   }
}